<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 人员管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button
                    type="primary"
                    icon="el-icon-delete"
                    class="handle-del mr10"
                    @click="delAllSelection"
                >批量删除</el-button>
                <el-button
                    type="primary"
                    icon="el-icon-plus"
                    class="handle-del mr10"
                    @click="handleAdd"
                >添加</el-button>
                <el-input v-model="query.name" placeholder="搜索内容" class="handle-input mr10" @keyup.enter.native='handleSearch'></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="50" align="center"/>
                <el-table-column  prop="id" label="ID" width="50" align="center">
                  <template slot-scope="scope">{{ getCurrentIDX(scope.$index + 1)}}</template>
                </el-table-column>
                <el-table-column prop="nickName" label="昵称" align="center">
                  <template slot-scope="scope">{{scope.row.nickName}}</template>
                </el-table-column>
                <el-table-column prop="sexual" label="性别" width="50" align="center">
                    <template slot-scope="scope">{{scope.row.sex}}</template>
                </el-table-column>
                <el-table-column prop="avatar" label="头像" width='90' align="center">
                    <template slot-scope="scope">
                      <el-image
                           class="table-td-thumb"
                           :src="scope.row.avatar"
                           :preview-src-list="[scope.row.avatar]"
                       ></el-image>
                    </template>
                </el-table-column>
                <el-table-column prop='level' label="会员等级" width="80" align="center">
                    <template slot-scope="scope">{{scope.row.level}}</template>
                </el-table-column>
                <el-table-column prop='integral' label="积分" align="center">
                    <template slot-scope="scope">{{scope.row.integral}}</template>
                </el-table-column>
                <el-table-column prop='userName' label="姓名" align="center">
                    <template slot-scope="scope">{{scope.row.userName}}</template>
                </el-table-column>
                <el-table-column prop='phoneNumber' label="电话" align="center">
                    <template slot-scope="scope">{{scope.row.phoneNumber}}</template>
                </el-table-column>
                <el-table-column prop='email' label="邮箱" align="center">
                    <template slot-scope="scope">{{scope.row.email}}</template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                            class='handle-button'
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red handle-button"
                            @click="handleDelete(scope.$index, scope.row.id)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="45%" class='dialog-form'>
          <el-form ref="form" :model="editForm" label-width="80px" :rules='rules'>
            <el-row type="flex" class="row-bg" justify="center">
              <el-col :span="11">
                <div class="grid-content bg-purple">
                  <el-form-item prop="nickName" label="昵称" class='itemRequired'>
                    <el-input v-model="editForm.nickName"></el-input>
                  </el-form-item>
                  <el-form-item label="性别" class='itemRequired'>
                    <el-select v-model="editForm.sex" placeholder="请选择">
                      <el-option v-for="item in sexOption" :key="item.key" :label="item.value" :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item prop="avatar" label="头像" class='itemRequired'>
                    <el-upload
                      class="avatar-uploader"
                      :action='qiniuAction'
                      :show-file-list="false"
                      :data='qiniuData'
                      :before-upload="beforeAvatarUpload"
                      :on-success='updateSuccess'
                      :on-error='updateError'
                      >
                      <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="11">
                <div class="grid-content bg-purple">
                  <el-form-item prop="userName" label="姓名" class='itemRequired'>
                    <el-input v-model="editForm.userName"></el-input>
                  </el-form-item>
                  <el-form-item prop="phoneNumber" label="电话" class='itemRequired'>
                    <el-input v-model="editForm.phoneNumber"></el-input>
                  </el-form-item>
                  <el-form-item prop="email" label="邮箱" class='itemRequired'>
                    <el-input v-model="editForm.email"></el-input>
                  </el-form-item>
                  <el-form-item label="会员等级" class='itemRequired'>
                    <el-input-number size="medium" v-model="editForm.level" :min="1" :max="10" label="会员等级"/>
                  </el-form-item>
<!--                  <el-form-item prop="password" label="密码" class='itemRequired'>-->
<!--                    <el-input v-model="editForm.password"></el-input>-->
<!--                  </el-form-item>-->
                </div>
              </el-col>
            </el-row>
          </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
<!--        添加弹出框-->
        <el-dialog title="添加" :visible.sync="addVisible" width="45%" class='dialog-form'>
            <el-form ref="form" :model="addForm" label-width="52px" :rules='rules'>
              <el-row type="flex" class="row-bg" justify="center">
                <el-col :span="11">
                  <div class="grid-content bg-purple">
                    <el-form-item prop="nickName" label="昵称" class='itemRequired'>
                      <el-input v-model="addForm.nickName"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" class='itemRequired'>
                      <el-select v-model="addForm.sex" placeholder="请选择">
                        <el-option v-for="item in sexOption" :key="item.key" :label="item.value" :value="item.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item prop="avatar" label="头像" class='itemRequired'>
                      <el-upload
                        class="avatar-uploader"
                        :action='qiniuAction'
                        :show-file-list="false"
                        :data='qiniuData'
                        :on-change="imgSaveToUrl"
                        :before-upload="beforeAvatarUpload"
                        :on-success="updateSuccess"
                        :on-error="updateError"
                      >
                        <img v-if="addForm.avatar" :src="addForm.avatar" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      </el-upload>
                    </el-form-item>
                  </div>
                </el-col>
                <el-col :span="11" :offset='1'>
                  <div class="grid-content bg-purple">
                    <el-form-item prop="userName" label="姓名" class='itemRequired'>
                      <el-input v-model="addForm.userName"></el-input>
                    </el-form-item>
                    <el-form-item prop="phoneNumber" label="电话" class='itemRequired'>
                      <el-input v-model="addForm.phoneNumber"></el-input>
                    </el-form-item>
                    <el-form-item prop="email" label="邮箱" class='itemRequired'>
                      <el-input v-model="addForm.email"></el-input>
                    </el-form-item>
                    <el-form-item prop="password" label="密码" class='itemRequired'>
                      <el-input v-model="addForm.password"></el-input>
                    </el-form-item>
                  </div>
                </el-col>
              </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios'

const sexOption = [
  {key: 1, value: '男'},
  {key: 2, value: '女'}
]

// 用户昵称
const nickNameValidate = (rule, value, callback) => {
    const reg = /^[\u4E00-\u9FA5\uf900-\ufa2d·s\-]{2,6}$/
    if (value === undefined || value === '') {
        callback(new Error('昵称不能为空'))
    } else if (!reg.test(value)) {
        callback(new Error('请输入2-6个汉字'))
    } else {
        callback()
    }
}
// 用户姓名
const userNameValidate = (rule, value, callback) => {
    const reg = /^[\u4E00-\u9FA5\uf900-\ufa2d·s\-]{2,6}$/
    if (value === undefined || value === '') {
        callback(new Error('姓名不能为空'))
    } else if (!reg.test(value)) {
        callback(new Error('请输入2-6个汉字！'))
    } else {
        callback()
    }
}
// 电话号码
const tellValidate = (rule, value, callback) => {
    const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
    if (value === undefined || value === '') {
        callback(new Error('电话不能为空'))
    } else if (!reg.test(value)) {
        callback(new Error('请输入正确的电话号码'))
    } else {
        callback()
    }
}
// 邮箱
const emailValidate = (rule, value, callback) => {
  const reg = /^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/
  if(value === undefined || value === '') {
    callback(new Error('邮箱不能为空'))
  } else if (!reg.test(value)) {
    callback(new Error('请输入正确的邮箱'))
  } else {
    callback()
  }
}
// 密码
const passwordValidate = (rule, value, callback) => {
    if (value === undefined || value === '') {
        callback(new Error('密码不能为空'))
    } else if (value.length < 6) {
        callback(new Error('密码不得少于6个字符'))
    } else {
        callback()
    }
}
export default {
    name: 'basetable',
    data() {
        return {
            query: {
                address: '',
                name: '',
                pageIndex: 1,
                pageSize: 20
            },
            tableData: [],
            multipleSelection: [],
            // 七牛云图片上传
            qiniuAction:"https://upload-z2.qiniup.com",//七牛云上传地址-华南
            qiniuData: {
              token: "",
              key: ''
            },
            qiniu_OutChain: 'http://qwq973aqg.hn-bkt.clouddn.com',//七牛云图片外链地址
            editVisible: false,
            addVisible :false,
            pageTotal: 0,
            sexOption,
            addForm: {
              avatar: 'http://jximg.iboy.tech/FgSXdN0LEwUbdNhPjta8FqgzImdS',
              sex: '男'
            },
            editForm:{},
            idx: -1,
            id: -1,
            // 表单验证提示
            rules: {
                nickName: [{ validator: nickNameValidate, trigger: 'blur'}],
                userName: [{ validator: userNameValidate, trigger: 'blur'}],
                phoneNumber: [{ validator: tellValidate, trigger: 'blur' }],
                email: [{ validator: emailValidate, trigger: 'blur' }],
                password: [{ validator: passwordValidate, trigger: 'blur' }]
            },
        };
    },
    created() {
        this.getData();
        this.getQiniuToken()
    },
    methods: {
        // 获取每条数据的序号
        getCurrentIDX(index) {
          return (this.query.pageIndex - 1) * this.query.pageSize + index
        },
        // 获取 easy-mock 的模拟数据
        getData() {
            const _this=this
            this.$http.get("/user/getAllUserInfo/"+_this.query.pageIndex+"/"+_this.query.pageSize)
              .then(res => {
                this.tableData = [];
                this.pageTotal= res.data.data.total;
                this.tableData = res.data.data.records;
              }).catch(error => {
                this.$message.error("获取用户信息失败")
                return false
              })
        },
        // 删除操作
        handleDelete(index, id) {
          // 二次确认删除
          this.$confirm('确定要删除吗？', '提示', {
            type: 'warning'
          }).then(() => {
              this.$http.delete("/user/del/"+id)
                .then(res => {
                  this.$message.success('删除成功');
                  this.tableData.splice(index, 1);
                })
            }).catch(err => {
              this.$message.error("删除失败")
            });
        },
        // 多选操作
        handleSelectionChange(val) {
          this.multipleSelection = val;
        },
        delAllSelection() {
          const length = this.multipleSelection.length;
          let str = '';
          for (let i = 0; i < length; i++) {
            const user = this.multipleSelection[i]
            this.$http.delete("/user/del/"+ user.id)
            // 删除
            for (let j = 0; j < this.tableData.length; j++) {
              if (this.tableData[j].id === user.id) {
                this.tableData.splice(j,1)
                break
              }
            }
            if (i < length - 1) {
              str += user.userName + '、';
            }
            else {
              str += user.userName + '。';
            }
          }
          this.multipleSelection = [];
          this.$message.success('删除了用户：' + str)
          return true
        },

        // 七牛云图片上传
        // 获得token
        getQiniuToken() {
          const _this = this
          this.$http.get('/qiniu/token')
            .then(res => {
              _this.qiniuData.token = res.data.data.token
            })
        },
        // 上传图片之前进行处理
        beforeAvatarUpload(file) {
          const isLt2M = file.size / 1024 / 1024 < 2;
          if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
            return false
          }
          this.qiniuData.key=`update_pic_${file.name}`
        },
        // 上传成功
        updateSuccess(res) {
          if (this.editVisible === true) {
            this.editForm.avatar = `${this.qiniu_OutChain}/${res.key}`
          } else if (this.addForm === true) {
            this.addForm.avatar = `${this.qiniu_OutChain}/${res.key}`
          }
        },
        // 上传失败
        updateError(err) {
          this.$message.error("上传失败,请重试!")
          return false
        },

        // 编辑操作
        handleEdit(index, row) {
          this.idx = index;
          this.editForm = Object.assign({}, row);
          // 清除表单验证
          this.$nextTick( () => {
            this.$refs.form.clearValidate()
          })
          this.editVisible = true;
        },
        // 保存编辑
        saveEdit() {
          this.$refs.form.validate(valid => {
            if (valid) {
              const _this = this
              this.$http.put("/user/editUser",this.editForm)
                .then(res => {
                  _this.editVisible = false;
                  _this.$set(_this.tableData, _this.idx, _this.editForm);
                  _this.getData()
                  _this.$message.success(`修改第 ${_this.idx + 1} 行成功`);
                  return true
                })
                .catch(err => {
                  _this.$message.error(`修改第 ${_this.idx + 1} 行失败`)
                  return false
                })
            }
          })
        },

        // 上传头像
        imgSaveToUrl(file) {
          let URL = window.URL || window.webkitURL;
          this.addForm.avatar = URL.createObjectURL(file.raw);
        },
        // 添加操作
        handleAdd() {
          this.addForm = {
            avatar: 'http://jximg.iboy.tech/FgSXdN0LEwUbdNhPjta8FqgzImdS',
            sex: '男'
          }
          // 清除表单验证
          this.$nextTick(() => {
            this.$refs.form.clearValidate()
          })
          this.addVisible = true;
        },
        // 保存添加
        saveAdd() {
          // 默认会员等级为1
          this.addForm.level = 1;
          // 默认积分为0
          this.addForm.integral = 0
          this.$refs.form.validate((valid) => {
            if (valid) {
              const _this = this
              this.$http.post("/user/addUser",this.addForm)
                .then(res =>{
                  if (res.data.code === 200) {
                    _this.addVisible = false;
                    _this.$set(this.tableData, this.idx, this.addForm);
                    _this.getData()
                    _this.$message.success(`添加成功`);
                    return true
                  } else {
                    _this.$message.error("昵称、姓名、电话、邮箱不能重复")
                  }
                })
                .catch(err => {
                  _this.$message.error(`添加失败`)
                  return false
                })
            }
          })
        },

        // 触发搜索按钮
        handleSearch() {
          const _this=this
          this.$http.get("http://47.104.251.133:8081/api/user/getUserByNickName/{nickname}?nickname=" + _this.query.name)
            .then(res => {
              _this.tableData = [];
              _this.tableData = res.data.data;
              _this.query.pageIndex = 1
              _this.pageTotal = res.data.data.length
            }).catch(error => {
               _this.$message.error('查询不到 ' + _this.query.name + ' 的信息')
              return false
            })
        },

        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        },
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}
.handle-select {
    width: 120px;
}
.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.dialog-form>>>div.el-dialog__header {
  border-bottom: 1px solid #cfcfcf;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.itemRequired>>>label.el-form-item__label::before {
    content: '* ';
    color: #F56C6C;
    margin-right: 2px;
}
.el-icon-plus {
  position: relative;
  top: -20px;
}
.avatar-uploader>>>div.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
}
.avatar-uploader>>>div.el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.handle-button {
  font-size: 14px;
}
</style>
